package algorithm;
class ListNode {
    int val;
    ListNode next;
    ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}

public class ReverseLinkedList {
    public static ListNode reverseList(ListNode head) {
        ListNode prev = null; // 用于记录当前节点的前一个节点，初始化为null
        ListNode current = head; // 当前节点，初始指向链表头
        ListNode nextTemp; // 用于临时保存当前节点的下一个节点

        while (current != null) {
            nextTemp = current.next; // 先保存当前节点的下一个节点，防止丢失后续链表
            current.next = prev; // 改变当前节点的指针方向，使其指向前一个节点
            prev = current; // 更新prev，使其指向下一次迭代的当前节点
            current = nextTemp; // 更新current，使其指向下一个节点，继续遍历
        }
        return prev; // 遍历结束后，prev指向的就是反转后的链表头
    }

    // 辅助方法，用于打印链表
    public static void printList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        // 创建链表 1 -> 2 -> 3 -> 4 -> 5
        ListNode head = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        head.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        System.out.println("原始链表:");
        printList(head);

        ListNode reversedHead = reverseList(head);
        System.out.println("反转后的链表:");
        printList(reversedHead);
    }
}